<?php
/**
 * LiveUrlController
 *
 * PHP Version 5.4
 *
 * @author liuxuTJ <liuxuphp@icesmart.cn>
 */
namespace Admin\Controller;

use Admin\Service\PermissionService;
use Admin\Service\UserService;
use Api\Controller\ServiceController;
use Model\LiveUrlModel;
use Model\RoomModel;
use Think\Controller;

/**
 * Class LiveUrlController
 */
class LiveUrlController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $userService = new UserService();
        $userInfo = $userService->validateLogin(); //验证是否登录

        $permissionService = new PermissionService();
        $permission = $permissionService->validate($userInfo['userId'], [
            'add' => '/'.CONTROLLER_NAME.'/add',
            'del' => '/'.CONTROLLER_NAME.'/delete',
            'edit' => '/'.CONTROLLER_NAME.'/edit',
        ]);

        $menu = $permissionService->menu($userInfo['userId']);

        $this->assign('menu', $menu);
        $this->assign('permission', $permission);
        $this->assign('userInfo', $userInfo);
    }

    /**
     * 直播地址列表
     */
    public function index()
    {
        $channel = uniqid();
        $liveUrlModel = new LiveUrlModel();
        $page       = $this->page($liveUrlModel, null);
        $show       = $page->show();
        $limit[] = $page->firstRow;
        $limit[] = $page->listRows;
        $liveUrl = $liveUrlModel->findByFilter(null,['id' => 'DESC'], $limit);
        $roomModel = new RoomModel();
        foreach($liveUrl as $k=>$v){
            $roomInfo = $roomModel->get($v['roomId']);
            $liveUrl[$k]['roomNumber'] = $roomInfo['roomNumber'];
        }

        $this->assign('url', '/LiveUrl/index');
        $this->assign("channel", $channel);
        $this->assign("liveUrl" ,$liveUrl);
        $this->assign("page", $show);
        $this->display();
    }

    /**
     * 添加直播地址
     *
     * @param string $address 直播地址
     * @param string $channel 通道名称
     *
     */
    public function add()
    {
        $data = [
            'address'    => $this->request->post('address'),
            'channel'    => $this->request->post('channel'),
            'play'    => $this->request->post('play'),
            'roomId'     => 0,
            'createTime' => date('Y-m-d h:l:s')
        ];
        if(empty($data['address']) || empty($data['channel']) || empty($data['play'])){
            $this->error("带*处为必填项");
        }
        $LiveUrlModel = new LiveUrlModel();
        $isHaveChannel = $LiveUrlModel->validateField('channel',$data['channel'],'unique');
        if($isHaveChannel){
            $LiveUrlId = $LiveUrlModel->add($data);
            if($LiveUrlId){
                $this->success("添加成功");
            }else{
                $this->error("添加失败");
            }
        }else{
            $this->error("通道名称已被占用");
        }
    }

    /**
     * 删除直播地址
     *
     * @param int $liveUrlId 直播地址ID
     */
    public function delete()
    {
        $liveUrlId     = intval($this->request->get('liveUrlId'));
        $LiveUrlModel  = new LiveUrlModel();
        $result = $LiveUrlModel->delete($liveUrlId);
        if ($result !==false) {
            $this->success("删除成功!");
        } else {
            $this->error("删除失败");
        }
    }

    /**
     * 修改直播地址
     *
     * @param int $liveUrlId  直播地址ID
     */
    public function edit(){

        $liveUrlId = intval($this->request->get('liveUrlId'));
        if(empty($liveUrlId)){
            $this->error("非法参数");
        }
        $liveUrlModel = new LiveUrlModel();
        $liveUrl = $liveUrlModel->get($liveUrlId);

        $this->assign('url', '/LiveUrl/index');
        $this->assign("liveUrl",$liveUrl);
        $this->display();
    }

    /**
     * 直播地址修改
     *
     * @param int    $id      直播Id
     * @param string $address 直播地址
     * @param string $channel 通道名称
     */
    public function save(){
        $id = intval($this->request->post('id'));
        $data = [
            'address'    => $this->request->post('address'),
            'channel'    => $this->request->post('channel'),
            'play'    => $this->request->post('play'),
            'status'    => $this->request->post('status')
        ];

        $liveUrlModel = new LiveUrlModel();
        if($this->request->post('status') == 0){
            //1.关闭直播间状态
            $LiveUrlInfo = $liveUrlModel->get($id);
            $roomModel = new RoomModel();
            $roomInfo = $roomModel->get($LiveUrlInfo['roomId']);
            if($roomInfo['status'] != 0){
                $updateRoom = $roomModel->buildQueryFilter(['id' => $LiveUrlInfo['roomId']])->setField('status' , 0);
                if($updateRoom == 0){
                    $this->error("关闭直播间失败");
                }
            }

            //2.关闭流通道
            $channel = $LiveUrlInfo['channel'];

            $apiService = new ServiceController();
            $stream = $apiService->getStream($channel);
            $cid = $stream['publish']['cid'];
            if($stream['publish']['active'] != 0){
                $offStream = $apiService->offStream($cid);
                if($offStream != 0){
                    $this->error("关闭流通道失败");
                }
            }
        }

        //3.关闭直播总闸
        $result = $liveUrlModel->update($data,$id);
        if($result !==false){
            $this->success("保存成功");
        }else{
            $this->error("保存失败");
        }

    }


}